package com.game.modular.game.playerInfo.service.base;

import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.game.playerInfo.mapper.PlayerRankMapper;
import com.game.modular.game.playerInfo.domain.PlayerRank;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;

/**
 * 基础服务-玩家信息
 *
 * @author cxy
 * @since 2024-09-23 14:13:02
 */
@Slf4j
@Service
public class PlayerRankBaseServiceImpl extends ServiceImpl<PlayerRankMapper, PlayerRank> implements IService<PlayerRank> {
    private static final String cacheKey = "player:%d:rank";
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    @Resource
    private ValueOperations<Object, PlayerRank> valueOperations;
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////  更新插入
    @Override
    public boolean updateById(PlayerRank entity) {
        boolean b = super.updateById(entity);
        saveCache(entity);
        return b;
    }
    @Override
    public boolean save(PlayerRank entity) {
        boolean save = super.save(entity);
        entity = super.getById(entity.getUid());
        savaCache(entity);
        return save;
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////  缓存部分
    public void savaCache(PlayerRank entity) {
        String key1 = String.format(cacheKey, entity.getUid());
        valueOperations.set(key1, entity);
        redisTemplate.expire(key1, 60, TimeUnit.MINUTES);
    }
    @Override
    public PlayerRank getById(Serializable id) {
        PlayerRank cache = getCache((Long) id);
        if (cache==null){
            cache =  super.getById(id);
        }
        return cache;
    }
    protected void saveCache(PlayerRank entity){
        String key1 = String.format(cacheKey, entity.getUid());
        valueOperations.set(key1, entity, 1, TimeUnit.DAYS);
    }
    private PlayerRank getCache(Long uid){
        String key1 = String.format(cacheKey,uid);
        return valueOperations.get(key1);
    }
}
